package soar.test.jpa.share;

import java.util.HashMap;
import java.util.Properties;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class Resource
{
    private final static Logger logger = LoggerFactory
            .getLogger(Resource.class);

    private static HashMap<Long, Resource> instances = new HashMap<Long, Resource>();

    public static Resource getInstance()
    {
        long thread_id = Thread.currentThread().getId();
        synchronized (instances)
        {
            Resource inst = instances.get(thread_id);
            if (inst == null)
            {
                inst = new Resource();
                instances.put(thread_id, inst);
            }
            return inst;
        }
    }

    public static HashMap<String, Properties> persistence_properties = new HashMap<>();

    public static void setPersistenceProperties(String persistence_unit,
            String db_type, String user, String password, String host,
            int port, String database)
    {
        Properties props = new Properties();
        props.setProperty("db_type", db_type.toLowerCase());
        props.setProperty("user", user);
        props.setProperty("password", password);
        props.setProperty("host", host);
        props.setProperty("port", "" + port);
        props.setProperty("database", database);
        persistence_properties.put(persistence_unit, props);
    }

    private HashMap<String, EntityManangerHandler> em_handlers = new HashMap<>();

    public EntityManangerHandler getEntityManagerHandler(String persistence_unit)
            throws Exception
    {
        EntityManangerHandler em_handler = em_handlers.get(persistence_unit);
        if (em_handler == null)
        {
            Properties props = persistence_properties.get(persistence_unit);
            if (props == null)
            {
                logger.info("persistence_unit({}) not found", persistence_unit);
                throw new Exception();
            }
            em_handler = new EntityManangerHandler(persistence_unit, props);
            em_handlers.put(persistence_unit, em_handler);
        }
        return em_handler;
    }
}
